import requests
from plotly.graph_objs import Bar
from plotly import offline

url = 'https://api.github.com/search/repositories?q=language:java&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
# print(f"Status Code: {r.status_code}")
response_dict = r.json()

# print(response_dict.keys())
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")

# 分析第一个仓库
# repo_dict = repo_dicts[0]
# print(f"\n Keys: {len(repo_dict)}")
# print('\n分析第一个仓库:')
# print(f"仓库名: {repo_dict['name']}")
# print(f"作者： {repo_dict['owner']['login']}")
# print(f"星: {repo_dict['stargazers_count']}")
# print(f"仓库地址: {repo_dict['html_url']}")
# print(f"创建时间: {repo_dict['created_at']}")
# print(f"更新时间: {repo_dict['updated_at']}")
# print(f"简介： {repo_dict['description']}")

# 分析返回的所有仓库
# for repo_dict in repo_dicts:
#     print(f"\n仓库名: {repo_dict['name']}")
#     print(f"作者： {repo_dict['owner']['login']}")
#     print(f"星: {repo_dict['stargazers_count']}")
#     print(f"仓库地址: {repo_dict['html_url']}")
repo_names, stars = [], []
for repo_dict in repo_dicts:
    repo_names.append(repo_dict['name'])
    stars.append(repo_dict['stargazers_count'])
data = [{
    'type': 'bar',
    'x': repo_names,
    'y': stars,
    'marker': {
        'color': 'rgb(60,100,150)',
        'line': {'width': 1.5, 'color': 'rgb(25,25,25)'}
    },
    'opacity': 0.6
}]
my_layout = {
    'title': 'GitHub上最受欢迎的java项目',
    'xaxis': {'title': '仓库名称'},
    'yaxis': {'title': '星数'}
}
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='java_repos.html')
